﻿using System;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using SARS.Biz;
using SARS.Entity;
using SARS.Utils;

namespace SARS.Account
{
    public partial class Login : Page
    {
        private readonly IAuthenticateBO _dao = new AuthenticateBO();

        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" +
                                            HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
        }

        protected void LoginButton_Click(object sender, EventArgs e)
        {
            UserEntity user = _dao.ValidateUser(LoginUser.UserName, LoginUser.Password);

            if (user != null)
            {
                if (user.UserRole > 0)
                {
                    Session["User"] = string.Format("{0} {1}", user.FirstName, user.LastName);
                    Session["Roles"] = user.UserRole;

                    ContextUtils.CurrentUser = user;
                    //Let us now set the authentication cookie so that we can use that later.
                    FormsAuthentication.SetAuthCookie(LoginUser.UserName, false);

                    //Set currrent user to session
                    Session["CurrentUser"] = user;

                    string strRedirect = Request["ReturnUrl"] ?? "~/Default.aspx";
                    Response.Redirect(strRedirect, true);
                }
                else
                    Response.Redirect("Login.aspx", true);
            }
            else
                Response.Redirect("Login.aspx", true);
        }
    }
}